package com.songcha.library_database_douyue.helper

import android.content.Context
import com.songcha.library_database_douyue.greendao.BookDownloadDBBeanDao
import com.songcha.library_database_douyue.greendao.BookTodayCommentWriteCountDBBeanDao
import com.songcha.library_database_douyue.greendao.DaoMaster
import com.songcha.library_database_douyue.greendao.TodayObtainGoldCountDBBeanDao
import com.songcha.library_database_douyue.greendao.TodayWatchRewardAdvertCountDBBeanDao
import org.greenrobot.greendao.database.Database

class MyDaoOpenHelper(context: Context,name:String):DaoMaster.OpenHelper(context,name) {
    //database upgrade
    override fun onUpgrade(db: Database?, oldVersion: Int, newVersion: Int) {
        super.onUpgrade(db, oldVersion, newVersion)

        if(db==null) return

        var tmpOldVersion=oldVersion
        if(tmpOldVersion==1 && newVersion>tmpOldVersion){
            dbUpgrade_1_2(db)
            tmpOldVersion=2
        }
        if(tmpOldVersion==2 && newVersion>tmpOldVersion){
            dbUpgrade_2_3(db)
            tmpOldVersion=3
        }
        if(tmpOldVersion==3 && newVersion>tmpOldVersion){
            dbUpgrade_3_4(db)
            tmpOldVersion=4
        }
        if(tmpOldVersion==4 && newVersion>tmpOldVersion){
            dbUpgrade_4_5(db)
            tmpOldVersion=5
        }


    }

    //1 to 2
    private fun dbUpgrade_1_2(db: Database){
        //read progress table add chapter_size field
        db.execSQL("alter table BOOK_READ_PROGRESS_DBBEAN add COLUMN \"CHAPTER_SIZE\" INTEGER NOT NULL DEFAULT 0")
        //add book download table
        BookDownloadDBBeanDao.createTable(db,true)
        //add today obtain gold table
        TodayObtainGoldCountDBBeanDao.createTable(db,true)
    }


    private fun dbUpgrade_2_3(db: Database){
        //alter today comment write count table filed name
        //sqlite3 need to drop table and re-create
        //db.execSQL("ALTER TABLE BOOK_TODAY_COMMENT_WRITE_COUNT_DBBEAN RENAME COLUMN \"COMMENT_WRITE_COUT\" TO \"COMMENT_WRITE_COUNT\"")
        db.execSQL("DROP TABLE IF EXISTS \"BOOK_TODAY_COMMENT_WRITE_COUNT_DBBEAN\"")
        BookTodayCommentWriteCountDBBeanDao.createTable(db,true)
        //add today watch reward advert count table
        TodayWatchRewardAdvertCountDBBeanDao.createTable(db,true)
    }

    private fun dbUpgrade_3_4(db: Database){
        db.execSQL("DROP TABLE IF EXISTS \"BOOK_TODAY_OBTAIN_GOLD_COUNT_DBBEAN\"")
        db.execSQL("DROP TABLE IF EXISTS \"BOOK_TODAY_WATCH_REWARD_ADVERT_COUNT_DBBEAN\"")
        TodayObtainGoldCountDBBeanDao.createTable(db,true)
        TodayWatchRewardAdvertCountDBBeanDao.createTable(db,true)
    }

    private fun dbUpgrade_4_5(db: Database){

    }
}